/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet.asynctasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.jaal.movilconsultanet.Progreso;
import com.jaal.movilconsultanet.R;
import com.jaal.movilconsultanet.Util;
import com.jaal.movilconsultanet.XMLContent;
import com.jaal.movilconsultanet.activities.Consulta;

public class SaldoRequester extends AsyncTask<String, Progreso, Boolean> {

	Consulta mainActivity;
	ProgressDialog progreso;
	Progreso progresoInfo = new Progreso();
	private String sessionId = null;
	String numero, password, codTlf;

	public SaldoRequester(Consulta mainActivity) {
		this.mainActivity = mainActivity;
	}

	@Override
	protected void onPreExecute() {
		progreso = new ProgressDialog(mainActivity);
		progreso.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progreso.setProgress(0);
		progreso.setMessage(mainActivity.getResources().getText(R.string.connection_connecting_server));
		progreso.setCancelable(false);
		progreso.show();
	}

	@Override
	protected Boolean doInBackground(String... urls) {

		Log.d("MCN", "GSMSessionStarter - inicio");
		// le paso el captcha cuando hago claseAsync.execute(captcha)
		sessionId = urls[0];
		HttpURLConnection connection = null;

		progresoInfo.setProgreso(10);
		progresoInfo.setMensaje(mainActivity,R.string.session_verifying);
		publishProgress(progresoInfo);
		connection = null;
		URL url = null;
		String targetURL = null;

		try {
			// Create connection
			targetURL = "http://www.movilnet.com.ve/agl/gsm/saldo/solicitudSaldo.action";
			url = new URL(targetURL);
			progresoInfo.setProgreso(20);
			progresoInfo.setMensaje(mainActivity,R.string.connection_connecting);
			publishProgress(progresoInfo);

			Log.d("MCN", "getSaldo - conectando..."+targetURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Cookie", sessionId);

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			connection.setConnectTimeout(5000);
			progresoInfo.setProgreso(50);
			progresoInfo.setMensaje(mainActivity,R.string.connection_response_get);
			publishProgress(progresoInfo);


			Map<String, List<String>> mapa = connection.getHeaderFields();

			Set<String> set = mapa.keySet();

			for (String string : set) {
				Log.d("MCN", "getUsuarioPerfil - headers..." + string+" : "+mapa.get(string));
			}


			String loc = connection.getHeaderField("content-location");

			if (loc != null && loc.equalsIgnoreCase("/finSesion.jsp")) {

				progresoInfo.setError(true);
				progresoInfo.setMensaje(mainActivity,R.string.session_expired);
				publishProgress(progresoInfo);

				return false;
			}

			Log.d("MCN", "getSaldo - getting response...");
			// Get Response
			InputStream is = connection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuilder response = new StringBuilder();

			// bytes que ignoro para mejorar eficiencia
			rd.skip(2900);

			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append("\r\n");
				Log.d("MCN", "getSaldo - response: "+line);
			}

			rd.close();


			//para generar el xml
			String contenido = "saldo";
			Map<String, Map<String, String>> data = new HashMap<String, Map<String, String>>();

			progresoInfo.setProgreso(55);
			progresoInfo.setMensaje(mainActivity,R.string.account_getting);
			publishProgress(progresoInfo);

			// Obtengo el balance o saldo
			Map<String, String> balance = Util.getRegExp("Balance Principal", response);
			data.put("balance", balance);

			Log.d("MCN", "getSaldo - put balance: "+data);

			progresoInfo.setProgreso(60);
			publishProgress(progresoInfo);

			
			// Obtengo los mensajes paquetes de texto
			
			Map<String, String> sms_pack = Util.getRegExp("Mensajes Paquetes de texto", response);
			data.put("sms_pack", sms_pack);

			Log.d("MCN", "getSaldo - put sms_pack: "+data);

			progresoInfo.setProgreso(65);
			publishProgress(progresoInfo);
			
			// Obtengo los segundos de plan de voz
			
			Map<String, String> voice_seconds = Util.getRegExp("Segundos Plan de Voz", response);
			data.put("voice_seconds", voice_seconds);
			
			Log.d("MCN", "getSaldo - put voice_seconds: "+data);

			progresoInfo.setProgreso(70);
			publishProgress(progresoInfo);

			// Obtengo los mensajes  de Asterisco Texto
			
			Map<String, String> asterisk_sms = Util.getRegExp("Asterisco Texto", response);
			data.put("asterisk_sms", asterisk_sms);

			Log.d("MCN", "getSaldo - put asterisk_sms: "+data);

			progresoInfo.setProgreso(75);
			publishProgress(progresoInfo);

			// Obtengo los mensajes Mensajes Plan de Voz
			Map<String, String> voice_sms = Util.getRegExp("Mensajes Plan de Voz", response);
			data.put("voice_sms", voice_sms);

			Log.d("MCN", "getSaldo - put voice_sms: "+data);

			progresoInfo.setProgreso(80);
			publishProgress(progresoInfo);

			// Obtengo los mensajes Mensajes Promocionales
			Map<String, String> promo_sms = Util.getRegExp("Mensajes Promocionales", response);
			data.put("promo_sms", promo_sms);

			Log.d("MCN", "getSaldo - put promo_sms: "+data);

			progresoInfo.setProgreso(85);
			publishProgress(progresoInfo);

			// Obtengo los Datos servicios
			Map<String, String> data_services = Util.getRegExp("Datos servicios", response);
			data.put("data", data_services);

			Log.d("MCN", "getSaldo - put data: "+data);
			
			progresoInfo.setProgreso(95);
			publishProgress(progresoInfo);

			// Obtengo los Datos servicios
			Map<String, String> voice_data = Util.getRegExp("Datos Plan de Voz", response);
			data.put("voice_data", voice_data);

			Log.d("MCN", "getSaldo - put data: "+data);

			XMLContent.saveXMLTree(contenido, data);

			progresoInfo.setProgreso(100);
			progresoInfo.setMensaje(mainActivity,R.string.account_got);
			progresoInfo.setFinished(true);
			publishProgress(progresoInfo);

		} catch (ConnectException e) {
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error);
			publishProgress(progresoInfo);
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo
			.setMensaje(mainActivity,R.string.connection_error_server);
			publishProgress(progresoInfo);
		} catch (IOException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error_io);
			publishProgress(progresoInfo);
		} finally {
			if (connection != null) {
				Log.d("MCN", "CaptchaRequester - desconectando...");
				connection.disconnect();
			}
		}
		return true;
	}

	@Override
	protected void onProgressUpdate(Progreso... values) {

		Progreso mProgresoInfo = values[0];

		if (!mProgresoInfo.isError()) {
			progreso.setProgress(mProgresoInfo.getProgreso());
			progreso.setMessage(mProgresoInfo.getMensaje());

			if (mProgresoInfo.isFinished()) {
				progreso.dismiss();
			}

		} else {
			progreso.dismiss();
			Toast.makeText(mainActivity, mProgresoInfo.getMensaje(),
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onPostExecute(Boolean result) {

		if (progresoInfo.isError()) {

			if (!result) {

				AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
				builder.setMessage(R.string.session_expired_msg)
				.setCancelable(false)
				.setIcon(R.drawable.ic_dialog_alert)
				.setPositiveButton(R.string.session_restart, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						new GSMSessionRestorer(mainActivity).execute("");
					}
				})
				.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();

			}	
			return;
		}

		mainActivity.refrescarSaldo();
	}

}
